package redisop

import (
	"fmt"
	"peilian-api/app/global/log"
	"peilian-api/app/global/variable"
	"time"

	"github.com/gin-gonic/gin"
)

const Nil = RedisError("redis: nil")

type RedisError string

func (e RedisError) Error() string { return string(e) }

// 获取redis
func GetStr(ctx *gin.Context, key string) (string, error) {
	var count = 1
	var s string = ""
	var err error = nil
	for {
		sc := variable.DB.Redis.Get(key)
		s, err = sc.Result()
		if err == nil {
			break
		}
		if err.Error() == Nil.Error() { // redis 找不到key
			err = nil
			break
		}
		if count == 3 {
			break
		}
		count++
	}
	// log.Logger.InfoF(ctx, fmt.Sprintf("retry count [%d], redis cmd [get], key: %s, err: %v", count, key, err))
	return s, err
}

// 获取redis
func SetStr(ctx *gin.Context, key, value string, expire time.Duration) error {
	sc := variable.DB.Redis.Set(key, value, expire)
	_, err := sc.Result()
	log.Logger.InfoF(ctx, fmt.Sprintf("redis cmd [set], key: %s,value:%s, expire:%v err: %v", key, value, expire, err))
	return err
}

// 删除redis
func DelKey(ctx *gin.Context, key string) error {
	sc := variable.DB.Redis.Del(key)
	_, err := sc.Result()
	log.Logger.InfoF(ctx, fmt.Sprintf("redis cmd [del], key: %s, err: %v", key, err))
	return err
}
